package com.neo.productitsms.http.framework;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
import com.neo.productitsms.R;
import com.neo.productitsms.utils.UIUtils;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Administrator on 2018/6/27.
 * 网路回调 统一处理 集成 统一 基类 baseBean
 */

public abstract class RequestStringCallBack implements Callback<String> {
    @Override
    public void onResponse(Call<String> call, Response<String> response) {
        if (response.raw().code() == 200) {
            String body = response.body();
            if (body == null) {
                onFail(UIUtils.getString(R.string.server_resp_error));
            } else {
                JsonParser parser = new JsonParser();
                JsonElement allElement = null;
                try {

                    allElement = parser.parse(body);
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                }

                if (allElement != null && !allElement.isJsonNull()) {

                    JsonObject allJsonObject = allElement.getAsJsonObject();

                    boolean res = allJsonObject.get("res").getAsBoolean();

                    if (res) {
                        onResponse(response);
                    } else {

                        String message = allJsonObject.get("message").getAsString();

                        onResFalse(message);
                    }


                } else {
                    onFail("数据 异常");
//                    onFail(UIUtils.getString(R.string.server_resp_error));
//                    throw new IllegalArgumentException("解析数据 异常");
                }

            }
        } else {
            onFail("链接异常");
        }
    }

    @Override
    public void onFailure(Call<String> call, Throwable t) {
        onFail(t.getMessage());
    }

    public abstract void onResponse(Response<String> response);

    public abstract void onResFalse(String message);

    public abstract void onFail(String errorMessage);

}
